package cz.muni.fi.pa165.hauntedhouses.service;

import cz.muni.fi.pa165.hauntedhouses.dao.HumanDAO;
import cz.muni.fi.pa165.hauntedhouses.dto.HouseDTO;
import cz.muni.fi.pa165.hauntedhouses.dto.HumanDTO;
import cz.muni.fi.pa165.hauntedhouses.entity.Human;
import cz.muni.fi.pa165.hauntedhouses.util.DTOAndDAOMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *A service layer for Human management.
 * All the transactions are controlled here.
 * Alows creation, update, remove, get and findBy.
 * @author Siliarus
 */
@Service
@Transactional
public class HumanServiceImpl implements HumanService{
    
    @Autowired
    private HumanDAO humanDAO;
    
    public void setHumanDAO(HumanDAO humanDao) {
        this.humanDAO = humanDao;
    }
    
    @Override
    public void create(HumanDTO human) {
        Human hm = DTOAndDAOMapper.DTOHumanToEntityHuman(human);
        humanDAO.create(hm);
        human.setId(hm.getId());
        human.getHome().setId(hm.getHome().getId());
    }


    @Override
    public void update(HumanDTO human) {
        Human humanDO = DTOAndDAOMapper.DTOHumanToEntityHuman(human);
        humanDAO.update(humanDO);
        human = DTOAndDAOMapper.HumanEntityToDTOHuman(humanDO);
    }

    @Override
    public void remove(HumanDTO human) {
        Human humanDO = DTOAndDAOMapper.DTOHumanToEntityHuman(human);
        humanDAO.remove(humanDO);
        
    }

    @Override
    public List<HumanDTO> findByName(String name) {
        List <HumanDTO> dtoList = new ArrayList<>();
        for (Human human : humanDAO.findByName(name)) {
            dtoList.add(DTOAndDAOMapper.HumanEntityToDTOHuman(human));
        }
        return Collections.unmodifiableList(dtoList);
    }

    @Override
    public List<HumanDTO> findAll() {
        List <HumanDTO> dtoList = new ArrayList<>();
        for (Human human : humanDAO.findAll()) {
            dtoList.add(DTOAndDAOMapper.HumanEntityToDTOHuman(human));
        }
        return Collections.unmodifiableList(dtoList);
    }

    @Override
    public List<HumanDTO> findByHouse(HouseDTO house) {
        List <HumanDTO> dtoList = new ArrayList<>();
        for (Human human : humanDAO.findByHouse(DTOAndDAOMapper.DTOHouseToEntityHouse(house))) {
            dtoList.add(DTOAndDAOMapper.HumanEntityToDTOHuman(human));
        }
        return Collections.unmodifiableList(dtoList);
    }

    @Override
    public HumanDTO get(Long id) {
        return DTOAndDAOMapper.HumanEntityToDTOHuman(humanDAO.get(id));
    }
    
}
